package org.sippr.controller;

import org.sippr.pojo.CreationImgSketch;
import org.sippr.pojo.Result;
import org.sippr.pojo.Server;
import org.sippr.service.CreationImgSketchService;
import org.sippr.service.ServerService;
import org.sippr.utils.SdRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/skecth")
public class CreationImgSketchController {
    @Autowired
    private CreationImgSketchService creationImgSketchService;
    @Autowired
    private ServerService serverService;

    @Value("${file.upload.path}")
    private String baseDirectory;

    //上传草图服务
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String oFile = file.getOriginalFilename();
        if (oFile == null)
            return Result.error("文件为空！");


        String filename = UUID.randomUUID().toString() + oFile.substring(oFile.lastIndexOf("."));
        Path dir = Paths.get(baseDirectory, "\\skech");
        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
        }

        Path filePath = dir.resolve(filename);
        file.transferTo(new File(filePath.toString()));


        //初始化类实例
        CreationImgSketch creationImgSketch = new CreationImgSketch();

        creationImgSketch.setName(filename);
        creationImgSketch.setSize(String.valueOf(file.getSize()));

        creationImgSketchService.add(creationImgSketch);

        Map<String, Object> body = new HashMap<>();
        body.put("skechImg", filename);


        //附加上处理过的预览图一起返回，显得高大上一些，其实没什么卵用
        //遍历服务器，找到空闲服务器
        List<Server> servers = serverService.findOnLineServers();
        if (!servers.isEmpty()) {
            //报警
            //如果有服务器在线，那么处理一下
            //这里不考虑机器是否繁忙，因为繁忙的机器也能即时做这个处理
            Server server = servers.get(0);
            String detectPngName = UUID.randomUUID().toString() + ".png";
            Path detectPngPath = dir.resolve(detectPngName);
            Boolean b = SdRequestUtils.SdControlNetDetect(server.getAddress(), filePath.toString(), detectPngPath.toString());
            if (b) {
                body.put("detectImg", detectPngName);
            }

        }

        return Result.success(body);
    }
}
